package com.zj.demo.aop;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class WebLogAspect {

	private static final Logger logger = LogManager.getLogger(WebLogAspect.class);

	@Pointcut("execution(public * com.zj.demo.ctrl.*.*(..))")
	public void webLog() {
	}

	/**
	 * @Before 在方法执行之前执行
	 */
	@Before("webLog()")
	public void doBefore() {
		// 接收请求，记录请求内容
		ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes();
		HttpServletRequest request = servletRequestAttributes.getRequest();
		// 记录以下内容
		logger.info("URL:" + request.getRequestURL().toString());
		logger.info("Method:" + request.getMethod());
		logger.info("IP:" + request.getRemoteAddr());
		// System.out.println("doBefore");
		Enumeration<String> enu = request.getParameterNames();
		while (enu.hasMoreElements()) {
			String name = enu.nextElement();
			logger.info("name{},value{}", name, request.getParameter(name));
		}
	}

	/**
	 * @After在方法执行之后执行
	 */
	@AfterReturning(returning = "ret", pointcut = "webLog()")
	public void doAfterReturning(Object ret) {
		// System.out.println("doAfter");
		logger.info("Response:" + ret);
	}
}
